/*
 * Copyright 2007-2010 GP Software
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * PropertiesExporter.java | Created on October 15, 2007
 */
package com.pacm.i18n;

import com.pacm.i18n.validator.Validator;
import com.pacm.i18n.validator.ValidatorException;
import com.pacm.i18n.validator.impl.InputValidator;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.*;


/**
 * Exports property files from an MS Excel sheet.
 *
 * @author Paul Augustine C. Mendoza
 * @since 1.0
 */
public class PropertiesExporter {

    /**
     * The Constant EXTENSION.
     */
    private static final String EXTENSION = ".properties";

    /**
     * The Constant DEFAULT_LOCALE.
     */
    private static final Locale DEFAULT_LOCALE = Locale.ENGLISH;

    /**
     * The logger
     */
    private static final Logger LOGGER = LoggerFactory
            .getLogger(PropertiesExporter.class);

    /**
     * The prefix.
     */
    private final String prefix;

    /**
     * The filename.
     */
    private final String filename;

    /**
     * The exported file list
     */
    private final List<File> fileList;

    /**
     * The base path
     */
    private String basePath;

    /**
     * Instantiates a new properties exporter.
     *
     * @param filename the filename
     * @param prefix   the prefix
     */
    public PropertiesExporter(String filename, String prefix) {
        this.filename = filename;
        this.prefix = prefix;
        this.fileList = new ArrayList<File>();
    }

    /**
     * Main launcher.
     *
     * @param args the args
     */
    public static void main(String[] args) {
        Validator validator = new InputValidator(args);
        try {
            validator.validate();
        } catch (ValidatorException ve) {
            LOGGER.error(ve.getMessage());
            System.exit(0);
        }
        PropertiesExporter exporter = new PropertiesExporter(args[0], args[1]);
        exporter.export();

    }

    /**
     * Exports resource bundles from a single Excel sheet to a list
     *
     * @return a list of exported files
     */
    public List<File> exportFileList() {
        this.export();
        return this.fileList;
    }

    /**
     * Exports resource bundles from a single Excel sheet.
     */
    @SuppressWarnings("unchecked")
    private void export() {
        try {
            URL url = this.getClass().getClassLoader()
                    .getResource(this.filename);
            this.basePath = new File(url.getPath()).getParent();
            POIFSFileSystem fs = new POIFSFileSystem(url.openStream());
            HSSFWorkbook wb = new HSSFWorkbook(fs);
            HSSFSheet sheet = wb.getSheetAt(0);
            HSSFRow headers = sheet.getRow((short) 0);
            String[] locales;
            int validColCount = 0;
            int colCount = headers.getPhysicalNumberOfCells();
            if (colCount < 1) {
                LOGGER.error("Malformed input file!");
                return;
            } else {
                // Truncate valid columns
                for (int i = 0; i < colCount; i++) {
                    HSSFCell cell = headers.getCell((short) (i + 1));
                    if (cell == null) {
                        break;
                    } else {
                        validColCount++;
                    }
                }
                locales = new String[validColCount];
                for (int idx = 0; idx < locales.length; idx++) {
                    HSSFCell cell = headers.getCell((short) (idx + 1));
                    if (cell == null) {
                        break;
                    }
                    locales[idx] = cell.getRichStringCellValue().getString();
                }
            }
            int idx = 1;
            Map<String, Collection> bundleMap =
                    new HashMap<String, Collection>();
            for (String locale : locales) {
                LOGGER.info("Locale = " + locale);
                Collection<KeyValue> bundleCollection =
                        new ArrayList<KeyValue>();
                Iterator iterator = sheet.rowIterator();
                while (iterator.hasNext()) {
                    HSSFRow row = (HSSFRow) iterator.next();
                    if (row.getCell((short) 0) == null) {
                        // Skip spaces
                        continue;
                    }
                    String key = row.getCell((short) 0)
                            .getRichStringCellValue().getString();
                    if (key.startsWith("#") || StringUtils.isWhitespace(key)) {
                        // Skip comments
                        continue;
                    }
                    HSSFCell valueCell = row.getCell((short) idx);
                    String valueStr = "";
                    if (valueCell != null) {
                        switch (valueCell.getCellType()) {
                            case HSSFCell.CELL_TYPE_STRING:
                                valueStr = valueCell
                                        .getRichStringCellValue().toString();
                                break;
                            case HSSFCell.CELL_TYPE_BOOLEAN:
                                valueStr = String.valueOf(valueCell
                                        .getBooleanCellValue());
                                break;
                            case HSSFCell.CELL_TYPE_NUMERIC:
                                valueStr = String.valueOf(valueCell
                                        .getNumericCellValue());
                                break;
                        }
                    }
                    KeyValue keyValue = new KeyValue();
                    keyValue.setKey(key);
                    keyValue.setValue(valueStr);
                    bundleCollection.add(keyValue);
                }
                idx++;
                bundleMap.put(locale, bundleCollection);
            }
            generateResourceBundles(bundleMap);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * Generates the resource bundles.
     *
     * @param bundleMap the bundle map
     * @throws IOException if file copy fails
     */
    @SuppressWarnings("unchecked")
    private void generateResourceBundles(Map<String, Collection> bundleMap)
            throws IOException {
        Set<String> keySet = bundleMap.keySet();
        File bundle = null;
        for (String locale : keySet) {
            // Create file
            BufferedWriter out = null;
            try {
                bundle = new File(this.basePath,
                        this.prefix + "_" + locale + EXTENSION);
                this.fileList.add(bundle);
                out = new BufferedWriter(new FileWriter(bundle));
                Collection<KeyValue> keyValues = bundleMap.get(locale);
                for (KeyValue keyValue : keyValues) {
                    out.write(keyValue.getKey() + "=" + keyValue.getValue());
                    out.newLine();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            // Copy default
            if (locale.equalsIgnoreCase(DEFAULT_LOCALE.getLanguage())) {
                File defaultBundle =
                        new File(this.basePath, this.prefix + EXTENSION);
                FileUtils.copyFile(bundle, defaultBundle);
            }
        }
        LOGGER.info(
                "See output files in this directory: " + this.basePath);
    }
}
